package com.sensePlusVR.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;

import com.sensePlusVR.bean.CollectionItem;
import com.sensePlusVR.bean.GameItem;
import com.sensePlusVR.bean.GameUrl;
import com.sensePlusVR.manager.DataCenter;
import com.sensePlusVR.manager.EventListener;
import com.sensePlusVR.manager.GameItemManager;
import com.sensePlusVR.realGame.RealGameVersion;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 更新游戏资源
 * @author: Loren
 * @create: 2017-5-9上午10:27:20
 * @desc: 
 *
 */
@SuppressLint("UseSparseArrays")
public class GameUpgradeUtils {
	private static final String TAG = GameUpgradeUtils.class.getSimpleName();
	public static final String DOWNLOADED_FROM_COLLCETION = "downloadFromCollection";
	public static final String DOWNLOADED_FROM_FOLLOWDETAILACTIVITY = "downloadFromFollowDetailActivity";
	
	private  Map<Integer, Boolean> mDeleted = new HashMap<Integer, Boolean>();
	private  DataCenter dataCenter = DataCenter.getInstans();
	private  static GameUpgradeUtils instance;
	private static Lock lock = new ReentrantLock();
	
	public static GameUpgradeUtils getInstance(){
		lock.lock();
		if (instance == null){
			instance = new GameUpgradeUtils();
		}
		lock.unlock();
		return instance;
	}
	
	public GameUpgradeUtils(){
		dataCenter.addGameEventListener(listener, this, TAG);
	}
	
	private EventListener listener = new EventListener(){
		@SuppressWarnings("unchecked")
		@Override
		public void Notify(int event, Object data, Object Params) {
			// TODO Auto-generated method stub
			if (Params == null || data == null)
				return;
			MyLog.e(TAG, "event = "+event);
			if (event == GameItemManager.EventGameItemRefreshGot || event == GameItemManager.EventGameItemActorName){
				List<GameItem> games = (List<GameItem>)data;
				for (GameItem i:games){
					int id = i.getId();
					MyLog.e(TAG, "id = "+id+" mDeleted size="+mDeleted.size());
					if (mDeleted.containsKey(id)){
						MyLog.e(TAG, "id = "+id+" mDeleted obj="+mDeleted.get(id));
							
						notifyUi();
						
						mDeleted.remove(id);
						
						MyLog.d(TAG, "download state 444 :　" + CollectionItem.query(i.getId()).getDownloadState());
						
						boolean isDownloading = CollectionItem.isDownloading(i);
						
						MyLog.d(TAG, "isDownloading : " + isDownloading);
								
						//需要继续下载的处理
						if (isDownloading){
							
							addDownloadResource(i);
							
							GameDownload.downloadGame(i);
							
						}
					}
				}
			}
		}
	};
	
	/**
	 * 没有下载：只更新GameItem本地SQLite
	 * @param gameItem
	 */
	public  void updateConfigNotDownload() {
		MyLog.d(TAG, "updateConfigNotDownload...");
		List<GameItem> gameList = GameItem.getGameListSort(true);

		if (gameList == null)
			return;
		boolean needReload = false;
		for (GameItem gameItem : gameList) {
			boolean isUpgrade = isToUpgradeGameItem(gameItem);
			boolean isRealGame = GameItem.isRealGame(gameItem);
			boolean isDownloadNone = CollectionItem.isDownloadNone(gameItem);
			
			MyLog.d(TAG, "isRealGame : " + isRealGame + " isUpgrade : " + isUpgrade);
			MyLog.d(TAG, "gameItem : " + gameItem);
			
			if (isUpgrade && isRealGame) {
				if (!isDownloadNone)
					continue;
				deleteGameItem(gameItem);
				needReload = true;
			}
		}
		if (needReload){
			reloadGameItems();
		}
	}
	

	/**
	 *  正在下载,暂停下载,下载错误：删除游戏资源及游戏数据库条目，及更新GameItem数据，然后重新下载
	 * 
	 * @param gameItem
	 */
	public  void updateConfigDownloading(List<GameItem> gameList) {
		
		MyLog.d(TAG, "updateConfigDownloading gameList : " + gameList.toString());
		
		boolean needReload = false;
		for (GameItem gameItem : gameList) {
			boolean isUpgrade = isToUpgradeGameItem(gameItem);
			boolean isRealGame = GameItem.isRealGame(gameItem);

			MyLog.d(TAG, "isRealGame : " + isRealGame + " isUpgrade : "
					+ isUpgrade);
			MyLog.d(TAG, "gameItem : " + gameItem);

			if (isUpgrade && isRealGame) {
				// 正在下载的更新游戏资源处理后继续下载（用户不感知）
				MyLog.d(TAG, "updateConfigDownloading to deletedownload");
				deleteDownloadResource(gameItem);
				deleteGameItem(gameItem);
				needReload = true;
			} else {
				//不需要更新的在重启应用后只对之前正在下载和下载错误做暂停下载处理
				if(CollectionItem.isDownloading(gameItem) || CollectionItem.isDownloadError(gameItem))
				GameDownload.downloadGame(gameItem);
			}
		}
		if (needReload){
			reloadGameItems();
		}
	}
	
	
	/**
	 * 已经下载： 删除游戏资源及游戏数据库条目，及更新GameItem数据
	 * @param gameItem
	 */
	public  void updateConfigDownloaded(final GameItem gameItem,
			Context context) {
		DialogUtils.showConfirmDialogConfirmCancel(context, null, "",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						
						dialog.dismiss();

						deleteDownloadResource(gameItem);

						deleteGameItem(gameItem);

						reloadGameItems();
						
					}

				}, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						dialog.dismiss();

					}
				});
	}
	
	public static boolean isToUpgradeGameItem(GameItem gameItem) {

		String gameConfig = GameDownload.getGameConfig(gameItem);
		boolean needUpgrade = RealGameVersion.needUpgade(gameConfig);

		if (needUpgrade)
			return true;
		return false;
	}
	
	private static void notifyUi(){
		EventBusUtils.notifyCollectionFragment();	
		EventBusUtils.notifyFollowDetailActivity();
	}
	
	private  void reloadGameItems(){
		dataCenter.getGameListSort(true, true, true);
	}
	/**
	 * 删除游戏资源及相应数据库条目
	 * 
	 * @param gameItem
	 */
	private static void deleteDownloadResource(GameItem gameItem) {

		CollectionItem clcItem = CollectionItem.query(gameItem.getId());
		
		MyLog.d(TAG, "download state 111 :　" + CollectionItem.query(gameItem.getId()).getDownloadState());

		if (clcItem == null) {

			return;
		}

		List<String> urls = GameDownload.GameUrls(gameItem);

		// 遍历url
		for (String url : urls) {
			
			MyLog.d(TAG, "url : " + url);
			
			GameUrl gameUrl = GameUrl.query(url);

			if (gameUrl != null) {
				
				MyLog.d(TAG, "gameUrl : " + gameUrl.toString());
				
				int count = gameUrl.getDownloadCount() - 1;
				
				//删除资源和数据
				if(count==0){
					
					//删除资源
					boolean isDelUrl = FileUtils.deleteFile(gameUrl.getSavePath());
					boolean isDelUrlTmp = FileUtils.deleteFile(gameUrl.getSavePath()+".tmp");
					
					MyLog.d(TAG, "isDelUrl : " + isDelUrl + " isDelUrlTmp : " + isDelUrlTmp);
					
					//更新数据库
					GameUrl.delete(gameUrl);
					
				}else{//仅仅更新数据
					
					gameUrl.setDownloadCount(count);
					
					GameUrl.saveOrUpdate(gameUrl);
				}
			}
		}
		
		MyLog.d(TAG, "download state 222 :　" + CollectionItem.query(gameItem.getId()).getDownloadState());
		
		//清除数据后把游戏状态设置为需要更新的临时状态（因为此处不做取消收藏处理，所以不能设置状态为仅仅收藏状态）
		clcItem.setDownloadState(CollectionItem.DownloadDoing);
		CollectionItem.saveOrUpdate(clcItem);
		
		MyLog.d(TAG, "download state 333 :　" + CollectionItem.query(gameItem.getId()).getDownloadState());
		
		
	}

	
	private static void addDownloadResource(GameItem gameItem) {
		//增加共有资源
		List<String> urls = GameDownload.GameUrls(gameItem);
		String savePath = GameDownload.getRootPath(gameItem);
		
		for(String url:urls){
			
			String fileName = FileUtils.getFileName(url);
			String filePath = savePath + File.separator + fileName;
			
			GameUrl gameUrl = GameUrl.query(url);
			
			if(gameUrl!=null){
				
				gameUrl.setDownloadCount(gameUrl.getDownloadCount()+1);
				
			}else{
				
				gameUrl = new GameUrl();
				
				gameUrl.setUrl(url);
				
				gameUrl.setSavePath(filePath);
				
				gameUrl.setFileName(fileName);
				
				gameUrl.setDownloadCount(1);
				
			}
			
			GameUrl.saveOrUpdate(gameUrl);
		}
	}
	
	
	/**
	 * 删除相应id的gameItem(按常规如果游戏有更新则服务器字段有更新，所以重新拉取数据会得到最新数据，此处不需要做删除处理)
	 * 
	 * @param gameItem
	 */
	@SuppressLint("UseValueOf")
	private  void deleteGameItem(GameItem gameItem) {
		MyLog.d(TAG, "deleteGameItem : " + gameItem);
		
		GameItem.deleteGameItem(gameItem);
		mDeleted.put(gameItem.getId(), new Boolean(true));
	}

}
